clear
clear matrix
clear mata
set matsize 11000
set maxvar 30000
set more off, perm
cd /Users/zachbrown/Projects/PriceTransparency/Data/


//////////////
// BUILD HHI
//////////////

use clean/radiology_visit_3.dta, clear

// Keep pre-period
keep if ym<ym(2007,3)

bys serv_prov_cw_key2: egen prov_id = mode(serv_ind_cw)
drop if prov_id==.

// Merge on county
rename serv_prov_zip zip
merge m:1 zip using dist/zcta_county_rel_10.dta
drop if _merge==2
rename zip serv_prov_zip
rename county serv_prov_county
drop _merge
drop if serv_prov_county==.

// Calculate market share by serv_prov_county proc_class
contract prov_id serv_prov_county proc_class, freq(n_visits)
bys serv_prov_county proc_class: egen total_visits = sum(n_visits)
gen market_share_sq = (n_visits / total_visits)^2
collapse (sum) hhi = market_share_sq (mean) total_visits, by(serv_prov_county proc_class)

save clean/hhi.dta, replace
